package org.wevil.service.sys;

import org.wevil.entity.sys.SysRes;
import org.wevil.props.ResProp;
import org.wevil.repo.sys.SysResRepo;
import org.wevil.util.ArrayUtil;
import org.wevil.util.BeanUtil;
import org.wevil.util.DateUtil;
import org.wevil.vo.list.ResListVo;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.transaction.Transactional;
import java.io.File;
import java.util.*;

@Service
@Transactional
public class ResService {

    @Resource
    private ResProp resProp;
    @Resource
    private SysResRepo repo;
    @Resource
    DownloadService downloadService;

    /**获取资源地址*/
    public String getPath(Integer id){
        ResListVo resListVo = getById(id);
        if(resListVo != null){
            return resListVo.getUri();
        }
        return null;
    }

    /** 获取多个资源地址 */
    public List<String> getPaths(List<Integer> ids){
        List<String> voList = new ArrayList<>();
        if(ids != null && ids.size()>0){
            ids.forEach(id -> {
                ResListVo resListVo = getById(id);
                if(resListVo != null){
                    voList.add(resListVo.getUri());
                }
            });
        }
        return voList;
    }

    /**
     * 获取资源路径
     * @param ids 资源id数组。示例：1,2,3
     * */
    public List<String> getPathsByStr(String ids){
        if(ids != null && ids.contains(",")){
            String[] split = ids.split(",");
            List<Integer> list = ArrayUtil.str2int(split);
            return getPaths(list);
        }
        if(ids != null && ids.trim().length()>0){
            ResListVo resListVo = getById(Integer.valueOf(ids));
            List<String> paths = new ArrayList<>();
            paths.add(resListVo.getUri());
            return paths;
        }
        return null;
    }

    /** 获取多个资源 */
    public List<ResListVo> getResVos(List<Integer> ids){
        List<ResListVo> voList = new ArrayList<>();
        if(ids != null && ids.size()>0){
            ids.forEach(id -> {
                ResListVo resListVo = getById(id);
                if(resListVo != null){
                    voList.add(resListVo);
                }
            });
        }
        return voList;
    }

    /**
     * 获取多个资源
     * @param ids 资源id数组。示例：1,2,3
     * */
    public List<ResListVo> getResVosByStr(String ids){
        if(ids != null && ids.contains(",")){
            String[] split = ids.split(",");
            List<Integer> list = ArrayUtil.str2int(split);
            return getResVos(list);
        }
        if(ids != null && ids.trim().length()>0){
            ResListVo resListVo = getById(Integer.valueOf(ids));
            List<ResListVo> vos = new ArrayList<>();
            vos.add(resListVo);
            return vos;
        }
        return null;
    }

    /**
     * 根据id获取资源信息
     * */
    public ResListVo getById(Integer id){
        Optional<SysRes> optional = repo.findById(id);
        if (optional.isPresent()) {
            SysRes entity = optional.get();
            return entity2vo(entity);
        } else {
            return null;
        }
    }

    // -------------------------------------------上传---------------------------------------------------------//

    /**
     * 文件上传
     * @param file 文件
     * */
    public ResListVo upload(MultipartFile file){
        // 服务器文件存储名称
        String fileName = UUID.randomUUID().toString();
        // 文件名后缀
        String fileEnd = "";
        String originalFilename = file.getOriginalFilename();
        if(originalFilename != null && originalFilename.contains(".")){
            fileEnd = originalFilename.substring(file.getOriginalFilename().lastIndexOf("."));
        }
        // 文件服务器存储路径
        String fileRoot = resProp.getRootPath();
        // 相对路径 时间戳 yyyy-MM-dd
        String relativePath = DateUtil.getDateStr() + "/";
        // 文件绝对路径
        String obPath = fileRoot  + relativePath + fileName + fileEnd;
        // 保存文件
        try {
            File dest = new File(obPath);
            File fileParent = dest.getParentFile();
            if (!fileParent.exists()) {
                fileParent.mkdirs();
            }
            file.transferTo(dest);
            String fileType = fileEnd.replace(".", "").trim().toLowerCase(Locale.ROOT);
            SysRes sysRes = new SysRes(fileName + fileEnd, originalFilename, relativePath, fileType);
            SysRes save = repo.save(sysRes);
            return entity2vo(save);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    // -------------------------------------------下载---------------------------------------------------------//

    /**
     * 根据资源id下载文件
     * */
    public void downloadById(Integer id){
        Optional<SysRes> optional = repo.findById(id);
        if (optional.isPresent()) {
            SysRes entity = optional.get();
            String fileName = entity.getName();
            String originName = entity.getOriginName();
            String relativePath = entity.getRelativePath();
            String abPath = resProp.getRootPath() + relativePath + fileName;
            downloadService.download(abPath, originName);
        }
    }

    /**
     * 根据文件名下载文件
     * */
    public void downloadByName(String fileRelativePath, String fileName){
        fileRelativePath = fileRelativePath == null ? "" : fileRelativePath;
        String abPath = resProp.getRootPath() + fileRelativePath + fileName;
        downloadService.download(abPath, fileName);
    }

    /** entity转vo */
    public ResListVo entity2vo(SysRes entity){
        ResListVo vo = new ResListVo();
        BeanUtil.copyPropIgnoreNull(entity, vo);
        String resPath = resProp.getMappingPath() + entity.getRelativePath();
        String resName = entity.getName();
        vo.setUri(resPath + resName);
        return vo;
    }

    // ---------------------------------------------私有方法---------------------------------------------//

}
